/**
 * 邮箱设置
 * */
import React, { useState } from 'react';
import { Table, Row, Form, Input, Button, DatePicker, message, Popconfirm } from 'antd';
import { history } from 'umi'
import { connect } from 'umi';
import moment from 'moment';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Pagination } from '@/components';
// import { Company } from '@/containers';
import authHelper from '@/utils/auth/helper';
import EmailSetting from './containers/EmailSetting';
import { Icon as CustomIcon } from '../components';
import { getEmailListPage, deleteEmail } from './service';

const { checkCode } = authHelper;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const format = val => val || '-';
const Email = ({ form, user }) => {
    const { firstOrgInfo = {} } = user;
    const { firstCompanyCode } = firstOrgInfo;
    const { getFieldDecorator, validateFields } = form;
    const [visible, setVisible] = useState(false);
    const [flag, setFlag] = useState(false);
    const [params, setParams] = React.useState({
        organizationCode: firstCompanyCode || '',
        pageNo: 1,
        pageSize: 10
    });

    // 获取邮箱列表
    const { data, loading } = useRequest(() => getEmailListPage(params), {
        refreshDeps: [params],
        ...defaultFormatResult
    });

    const emailList = data?.rows || [];
    const total = data?.total || 0;

    const { loading: deleteLoading, run: handleDeleteEmail } = useRequest(value => deleteEmail(value), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                setParams({
                    ...params,
                    pageNo: 1
                });
                message.success(msg);
            } else {
                message.error(msg);
            }
        }
    });

    const handleOnDelete = id => {
        if (id) {
            handleDeleteEmail(id);
        }
    };

    const columns = [
        {
            title: '邮箱',
            dataIndex: 'email'
        },
        {
            title: '姓名',
            dataIndex: 'employeeName',
            render: format
        },
        {
            title: '行政机构',
            dataIndex: 'organizationName',
            render: format
        },
        {
            title: '时间',
            dataIndex: 'createTime',
            sorter: () => {},
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : text)
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 100,
            render: (text, record) =>
                checkCode('office:recruitment:setting:email:delete') && (
                    <div style={{ display: 'flex' }}>
                        <Popconfirm
                            title="确定要删除邮箱吗?"
                            onConfirm={() => handleOnDelete(record?.id)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <CustomIcon title="删除" type="listfunction_delete_icon_default" />
                        </Popconfirm>
                    </div>
                )
        }
    ];

    const handleSearch = e => {
        e.preventDefault();
        validateFields((err, values) => {
            if (err) {
                return;
            }
            const { rangeDate, organizationCode, ...rest } = values;
            setParams({
                ...params,
                ...rest,
                organizationCode: organizationCode || firstCompanyCode,
                createStartDate: rangeDate?.length > 0 ? rangeDate[0].format('YYYY-MM-DD') : '',
                createEndDate: rangeDate?.length > 1 ? rangeDate[1].format('YYYY-MM-DD') : '',
                pageNo: 1
            });
        });
    };

    // 保存成功
    const handleSave = value => {
        if (value) {
            setParams({
                ...params,
                pageNo: 1
            });
        }
        setVisible(false);
    };

    const handleCancel = () => {
        setVisible(false);
    };

    // 新增邮箱
    const handleAddEmail = () => {
        setVisible(true);
    };

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        setParams({
            ...params,
            pageNo: current,
            pageSize
        });
    };

    const handleTableChange = (_, _filters, sorter) => {
        const { field, order } = sorter;
        setParams({
            ...params,
            orderByField: order ? `${field}|${order}`.replace('end', '') : '',
            pageNo: 1
        });
    };

    return (
        <>
            <Row type="flex" justify="space-between" style={{ marginBottom: 12 }}>
                <div style={{ flex: 1 }}>
                    <Form onSubmit={handleSearch} layout="inline">
                        <Row>
                            <Form.Item label="邮箱">
                                {getFieldDecorator('email')(
                                    <Input placeholder="请输入邮箱" style={{ width: 148 }} allowClear />
                                )}
                            </Form.Item>
                            <Form.Item>
                                <Button type="link" style={{ padding: 0 }} onClick={() => setFlag(!flag)}>
                                    高级搜索
                                </Button>
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    搜索
                                </Button>
                            </Form.Item>
                        </Row>
                        <Row style={flag ? { display: 'block' } : { display: 'none' }}>
                            {/* <Form.Item label="行政机构">
                                {getFieldDecorator('organizationCode', {
                                    initialValue: undefined
                                })(
                                    <Company
                                        permissionsLimit={false}
                                        style={{ width: 148 }}
                                        placeholder="请选择行政机构"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    />
                                )}
                            </Form.Item> */}
                            <Form.Item label="姓名">
                                {getFieldDecorator('employeeName')(
                                    <Input placeholder="请输入" style={{ width: 148 }} allowClear />
                                )}
                            </Form.Item>
                            <Form.Item label="时间区间">
                                {getFieldDecorator('rangeDate')(
                                    <RangePicker format={dateFormat} style={{ width: 220 }} />
                                )}
                            </Form.Item>
                        </Row>
                    </Form>
                </div>
                <div style={{ display: 'flex', height: 40, alignItems: 'center' }}>
                    {checkCode('office:recruitment:setting:email:record') && (
                        <Button
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/recruitment/email/history'
                                });
                            }}
                        >
                            获取记录
                        </Button>
                    )}
                    {checkCode('office:recruitment:setting:email:create') && (
                        <Button type="primary" onClick={handleAddEmail} style={{ marginLeft: 12 }}>
                            + 新增邮箱
                        </Button>
                    )}
                </div>
            </Row>
            <Table
                rowKey="id"
                dataSource={emailList}
                columns={columns}
                loading={loading || deleteLoading}
                pagination={false}
                onChange={handleTableChange}
            />
            <Pagination
                current={params?.pageNo || 1}
                pageSize={params?.pageSize || 10}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
            <EmailSetting handleSave={handleSave} visible={visible} handleOnCancel={handleCancel}></EmailSetting>
        </>
    );
};

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(Email));
